package com.daqian.mall.exception;

import com.daqian.mall.rest.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;


@ControllerAdvice
@RestController
@Slf4j
public class ExceptionController extends DefaultErrorAttributes {

    /**
     * 全局异常通知，包括aop的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public RestResult exceptionNotify(Exception e) {
        log.error(e.getMessage(), e);
        return RestResult.fail("服务器繁忙，请稍后再试");
    }


    /**
     * 数字转换异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = NumberFormatException.class)
    public RestResult numberFormatException(Exception e) {
        return RestResult.msg(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }

    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public RestResult httpMessageNotReadableException(Exception e) {
        return RestResult.msg(HttpStatus.BAD_REQUEST.value(), e.getMessage());
    }


    /**
     * 请求参数数据类型不匹配
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public RestResult bindException(Exception e) {
        return RestResult.msg(HttpStatus.BAD_REQUEST.value(), "请求参数数据类型不匹配");
    }

    /**
     * 打印自定义异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = ServiceException.class)
    public RestResult ServiceException(ServiceException e) {
//        if (ServiceException.SHOW_ERROR != e.getCode()) {
//            return exceptionNotify(e);
//        } else {
//            log.error(e.getMessage(), e);
//            return RestResult.fail(e.getMessage());
//        }
        log.error(e.getMessage(), e);
        return RestResult.fail(e.getCode(), e.getMessage());
    }


    /**
     * 参数错误
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = IllegalArgumentException.class)
    public RestResult illegalArgumenException(IllegalArgumentException e) {
        return RestResult.fail(e.getMessage());
    }

    /**
     * 请求方法错误
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public RestResult requestMethodErrorException(HttpRequestMethodNotSupportedException e) {
        return RestResult.msg(e.getMessage());
    }
}